﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;

public class MyCarManagerActivity extends BaseActivity_NoBar implements
		OnClickListener {
	private int carInfoIndex;
	private TextView car_number_tv;
	private TextView car_brand_tv;
	private TextView car_annual_audit_deadline_tv;
	private TextView car_insurance_deadline_tv;
	private List<VehicleInfo> vehicleInfos;
	private VehicleInfo vehicleInfo;
	private TextView my_car_info_back_btn;
	private TextView save_car_info_btn;
	private Button delete_car_info_btn;
	private String car_number;
	private String car_brand;
	private String car_insurance_deadline;
	private String car_annual_audit_deadline;
	private DataLoader dataLoader;
	private View choose_car_brand;
	private View choose_car_annual_audit_deadline;
	private View choose_car_insurance_deadline;
	private Intent intent = new Intent();
	private String pp;
	private String xh;
	private DatePickerDialog datepick;
	protected String year;
	protected String month;
	protected String day;
	protected String endtiem;
	public static final int CHOOSE_BRAND = 1;
	private static final int ANNUAL_AUDIT_DEADLINE = 2;
	private static final int CAR_INSURANCE_DEADLINE = 3;
	private static final int CHOOSE_DATE = 0;
	public static final int INPUT_LINCENSE_PLATE_NUMBER = 123;
	private int flag;

	private DatePickerDialog.OnDateSetListener mSetDateListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int myear, int monthOfYear,
				int dayOfMonth) {
			year = myear + "";
			month = monthOfYear + 1 + "";
			day = dayOfMonth + "";

			calendar.set(Calendar.YEAR, myear);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			// week = int_to_str(calendar.get(Calendar.DAY_OF_WEEK));
			endtiem = year + "-" + month + "-" + day;
			if (ANNUAL_AUDIT_DEADLINE == flag) {
				car_annual_audit_deadline_tv.setText(year + "-" + month + "-"
						+ day);
			} else {
				car_insurance_deadline_tv.setText(year + "-" + month + "-"
						+ day);
			}

		}
		// }
	};
	private Calendar calendar;
	private View input_license_plate_number_goto;
	
	private Handler handler = new Handler() {
		private ProApplication application;

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							// 更改CarListAdapter中的数据
							JSONObject jo = new JSONObject(result);
							String vehicleId = jo.optString("vehicleId");
							Intent intent = new Intent();
							intent.putExtra("pp", pp);
							intent.putExtra("xh", xh);
							intent.putExtra("car_number", car_number);
							intent.putExtra("car_annual_audit_deadline",
									car_annual_audit_deadline);
							intent.putExtra("car_insurance_deadline", car_insurance_deadline);
							intent.putExtra("carID", vehicleId);
							//vehicleInfo.setInspectionExpireTime(inspectionExpireTime);
							setResult(MainConstants.SUCCESS, intent);
							MyCarManagerActivity.this.finish();
//							Toast.makeText(MyCarManagerActivity.this,"添加成功", 0).show();
							finishProgress();
						} else {
							finishProgress();
						}
					} catch (JSONException e) {
						Toast.makeText(MyCarManagerActivity.this,"登录失败", 0).show();
						e.printStackTrace();
						finishProgress();
					}
				} else {
					Toast.makeText(MyCarManagerActivity.this, "登录失败,网络错误!", 0).show();
					finishProgress();
				}
				break;
			case HttpTask.RESULT_ERROR:
				Toast.makeText(MyCarManagerActivity.this, "网络错误!", 0).show();
				finishProgress();
				break;
			}
		}
	};
	private int userId;

	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_car_manager);
		this.findControlView();
		userId = SharePrefenceUtil.getUserID(MyCarManagerActivity.this);
		carInfoIndex = getIntent().getIntExtra("carInfoIndex", -1);
		if (!(carInfoIndex == -1)) {
			vehicleInfos = (List<VehicleInfo>) ObjectCache.get("vehicleInfos");
			vehicleInfo = vehicleInfos.get(carInfoIndex);
		} else {

		}

		calendar = Calendar.getInstance();
		this.setContentForControlView();
		this.registerListener();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case CHOOSE_BRAND:// 选择品牌
			if(null != data){
				pp = data.getStringExtra("pp");
				xh = data.getStringExtra("xh");
				car_brand_tv.setText(pp + "  " + xh);
			}
			break;
		case INPUT_LINCENSE_PLATE_NUMBER:
			if(null == data){
				
			}else {
				String province = data.getStringExtra("province");
				String car_number = data.getStringExtra("car_number");
				car_number_tv.setText(province+car_number);
			}
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case CHOOSE_DATE:
			if (null == vehicleInfo) {
				datepick = new DatePickerDialog(this, mSetDateListener,
						calendar.get(Calendar.YEAR),
						calendar.get(Calendar.MONTH),
						calendar.get(Calendar.DAY_OF_MONTH));
				return datepick;
			} else {
				String date[] = vehicleInfo.getInsuranceStartTime().split("-");
				datepick = new DatePickerDialog(this, mSetDateListener,
						Integer.parseInt(date[0]),
						Integer.parseInt(date[1]) - 1,
						Integer.parseInt(date[2]));
				return datepick;
			}
		}
		return datepick;
	}

	private void findControlView() {
		// 车牌号
		input_license_plate_number_goto = this
				.findViewById(R.id.input_license_plate_number_goto);
		car_number_tv = (TextView) this.findViewById(R.id.car_number_tv);
		// 车品牌
		choose_car_brand = this.findViewById(R.id.choose_car_brand);
		car_brand_tv = (TextView) this.findViewById(R.id.car_brand_tv);
		// annual audit deadline
		choose_car_annual_audit_deadline = this
				.findViewById(R.id.choose_car_annual_audit_deadline);
		car_annual_audit_deadline_tv = (TextView) this
				.findViewById(R.id.car_annual_audit_deadline_tv);
		// car insurance deadline
		choose_car_insurance_deadline = this
				.findViewById(R.id.choose_car_insurance_deadline);
		car_insurance_deadline_tv = (TextView) this
				.findViewById(R.id.car_insurance_deadline_tv);
		// 返回
		my_car_info_back_btn = (TextView) this
				.findViewById(R.id.my_car_info_back_btn);
		// 保存carinfo
		save_car_info_btn = (TextView) this
				.findViewById(R.id.save_car_info_btn);
		save_car_info_btn.setTextColor(getResources().getColor(R.color.white));
	}

	private void setContentForControlView() {
		/*
		 * if(1024 == carInfoIndex){
		 * 
		 * }else { car_number_et.setText(vehicleInfos.get(carInfoIndex).
		 * getLicensePlateNumber());
		 * car_brand_tv.setText(vehicleInfo.getVehicleBrand());
		 * //car_annual_audit_deadline_et.setText();//接口待定
		 * //car_insurance_deadline_et // 待定 }
		 */
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.my_car_info_back_btn:
			this.finish();
			break;
		case R.id.save_car_info_btn:
			car_number = car_number_tv.getText().toString();
			car_brand = car_brand_tv.getText().toString();
			car_annual_audit_deadline = car_annual_audit_deadline_tv.getText().toString();
			car_insurance_deadline = car_insurance_deadline_tv.getText().toString();
			if("".equals(car_brand)){
				showToast("车型为空");
				break;
			}
			if ("".equals(car_number)) {
				showToast("车牌号为空");
				break;
			} 
			else {
				// 将添加的Car信息提交服务器
				//showToast("待传入服务器");
				List<NameValuePair> params1 = new ArrayList<NameValuePair>();
				params1.add(new BasicNameValuePair("userId", userId + ""));
				params1.add(new BasicNameValuePair("vehicleBrand",pp));
				params1.add(new BasicNameValuePair("vehicleModels",xh));
				params1.add(new BasicNameValuePair("licensePlateNumber",car_number));
				if(null != car_annual_audit_deadline&&!"".equals(car_annual_audit_deadline)){
					params1.add(new BasicNameValuePair("inspectionExpireTime",car_annual_audit_deadline.replaceAll("-", "/")));
				}
				if(null != car_insurance_deadline&&!"".equals(car_insurance_deadline)){
					params1.add(new BasicNameValuePair("insuranceEndTime",car_insurance_deadline.replaceAll("-", "/")));
				}
				new DataLoader(MyCarManagerActivity.this).DisplayData(MainConstants.HOST_test
						+ HttpConfigAPI.ADD_VEHICLE, params1, handler, "", false);
				showProgress("正在加载数据...");
			}
			break;

		case R.id.choose_car_brand:
			qStartActivityForResult(XgcxActivity.class, null, CHOOSE_BRAND);
			break;
		case R.id.choose_car_annual_audit_deadline:
			flag = ANNUAL_AUDIT_DEADLINE;
			showDialog(CHOOSE_DATE);
			break;
		case R.id.choose_car_insurance_deadline:
			flag = CAR_INSURANCE_DEADLINE;
			showDialog(CHOOSE_DATE);
			break;
		case R.id.input_license_plate_number_goto:
			qStartActivityForResult(LincensePlateNumberActivity.class, null,
					INPUT_LINCENSE_PLATE_NUMBER);
			break;
		default:
			break;
		}

	}

	private void registerListener() {
		my_car_info_back_btn.setOnClickListener(this);
		choose_car_brand.setOnClickListener(this);
		choose_car_annual_audit_deadline.setOnClickListener(this);
		choose_car_insurance_deadline.setOnClickListener(this);
		input_license_plate_number_goto.setOnClickListener(this);
		save_car_info_btn.setOnClickListener(this);
	}
}
